package com.fulihui.systemcore.service;

import com.alibaba.fastjson.JSONObject;
import com.fulihui.systemcore.api.QiniuUploadTokenConfigService;
import com.fulihui.systemcore.dal.dataobj.PropertiesExample;
import com.fulihui.systemcore.domain.QiniuConfig;
import com.fulihui.systemcore.dto.PropertiesDTO;
import com.fulihui.systemcore.repository.PropertiesRepository;
import com.fulihui.systemcore.request.qiniu.QiniuUploadTokenConfigRequest;
import com.fulihui.systemcore.response.qiniu.QiniuUploadTokenConfigResult;
import com.qiniu.util.Auth;
import org.apache.dubbo.config.annotation.Service;
import org.near.servicesupport.error.CommonServiceErrorEnum;
import org.near.servicesupport.result.ResultBuilder;
import org.near.toolkit.common.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.UUID;

/**
 * @author Created by Willard.Hu on 2016/8/11 0011.
 */
@Service(version = "1.0.0")
public class QiniuUploadTokenConfigServiceImpl implements QiniuUploadTokenConfigService {
    @Autowired
    private PropertiesRepository propertiesRepository;
    @Value("${product.env}")
    private String               envType;

    @Override
    public QiniuUploadTokenConfigResult query(QiniuUploadTokenConfigRequest request) {
        PropertiesExample example = new PropertiesExample();
        example.createCriteria().andProdNameEqualTo(request.getBizType())
                .andEnvTypeEqualTo(envType)
                .andPropKeyEqualTo("QINIU_CONFIG");
        List<PropertiesDTO> propList = propertiesRepository.query(example);
        // 应该只能查出一个属性配置
        if (CollectionUtils.isEmpty(propList) || propList.size() != 1) {
            return ResultBuilder.fail(QiniuUploadTokenConfigResult.class,
                    CommonServiceErrorEnum.REQUEST_PARAMETER_ERROR);
        }

        String qiniuConfigJson = propList.get(0).getValue();
        QiniuConfig qiniuConfig = JSONObject.parseObject(qiniuConfigJson, QiniuConfig.class);
        Auth auth = Auth.create(qiniuConfig.getQiniuAccessKey(), qiniuConfig.getQiniuSecretKey());
        String token = auth.uploadToken(qiniuConfig.getQiniuImageSpace());

        QiniuUploadTokenConfigResult result = ResultBuilder
                .succ(QiniuUploadTokenConfigResult.class);
        result.setUploadToken(token);
        result.setSpace(qiniuConfig.getQiniuImageSpace());
        result.setImageURL(qiniuConfig.getQiniuImageUrl());
        result.setUnioName(StringUtil.replace(UUID.randomUUID().toString(), "-",
                StringUtil.EMPTY_STRING));
        return result;
    }

}
